package com.mz.ozy.activity.login;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.mz.ozy.R;
import com.mz.ozy.activity.MainActivity;
import com.mz.ozy.activity.me.CustomServiceActivity;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.AlipayAuthBean;
import com.mz.ozy.bean.CheckBean;
import com.mz.ozy.bean.LoginBean;
import com.mz.ozy.bean.NetBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.CodePresenter;
import com.mz.ozy.mvp.presenter.LoginPresenter;
import com.mz.ozy.mvp.view.CodeContract;
import com.mz.ozy.mvp.view.LoginContract;
import com.mz.ozy.utils.AppUtils;
import com.mz.ozy.utils.CodeHelper;
import com.mz.ozy.utils.SPUtils;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.widget.LoginButtonSpan;
import com.mz.ozy.widget.dialog.BaseDialog;
import com.mz.ozy.widget.dialog.CheckDialog;
import com.socks.library.KLog;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 手机登录
 */
public class PhoneSmsLoginActivity extends BaseActivity<LoginContract.View, LoginPresenter> implements LoginContract.View, CodeContract.View {

    public static final int LOGIN_MODE_CODE = 0;
    public static final int LOGIN_MODE_PASSWORD = 1;

    @BindView(R.id.etPhone)
    EditText mEtPhone;
    @BindView(R.id.etCode)
    EditText mEtCode;
    @BindView(R.id.tv_get_code)
    TextView mTvGetCode;
    @BindView(R.id.bt_login)
    Button mBtLogin;
    @BindView(R.id.alipayIv)
    ImageView mAlipayIv;
    @BindView(R.id.tv_service_agreement)
    TextView mTvServiceAgreement;
    @BindView(R.id.tv_privacy_policy)
    TextView mTvPrivacyPolicy;
    @BindView(R.id.tv_login_title)
    TextView mTvLoginTitle;
    @BindView(R.id.tv_login_tip_msg)
    TextView mTvLoginTipMsg;
    @BindView(R.id.tv_register_tip_msg)
    TextView mTvRegisterTipMsg;
    @BindView(R.id.etPwd)
    EditText mEtPwd;
    @BindView(R.id.ll_codeView)
    LinearLayout mLlCodeView;
    @BindView(R.id.wechatIv)
    ImageView mWechatIv;
    @BindView(R.id.tv_agree_service_agreement)
    CheckBox mAgree;

    private int loginMode = LOGIN_MODE_CODE;//登录模式
    private CodeHelper codeHelper;
    private CodePresenter mCodePresenter;

    //微信授权数据
    private String wx_useravatar;
    private String wx_nickname;
    private String wx_sex;
    private String uid = "";
    private String unionid = "";
    private int mType = LoginPresenter.AUTH_TYPE_WX;
    private String auth_code;
    private String user_id;
    private Boolean agreeCheckBoxIsTrue=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_login);
        ButterKnife.bind(this);
        initTitle();
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(PhoneSmsLoginActivity.this, MainActivity.class));
                finish();
            }
        });
        codeHelper = new CodeHelper(this, mTvGetCode);
        mCodePresenter = new CodePresenter(this);
        rightTextView.setText(R.string.account_pass_login_label);
        rightTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (loginMode == LOGIN_MODE_CODE) {
                    loginMode = LOGIN_MODE_PASSWORD;
                    rightTextView.setText(R.string.phone_code_login_label);
                    mTvLoginTitle.setText(R.string.pwd_login);
                    mTvLoginTipMsg.setVisibility(View.INVISIBLE);
                    mTvRegisterTipMsg.setVisibility(View.GONE);
                    mLlCodeView.setVisibility(View.GONE);
                    mEtPwd.setVisibility(View.VISIBLE);
//                    mEtPhone.setHint(R.string.hint_user);
                } else {
                    loginMode = LOGIN_MODE_CODE;
                    rightTextView.setText(R.string.account_pass_login_label);
                    mTvLoginTitle.setText(R.string.login);
                    mTvLoginTipMsg.setVisibility(View.VISIBLE);
                    mTvRegisterTipMsg.setVisibility(View.VISIBLE);
                    mLlCodeView.setVisibility(View.VISIBLE);
                    mEtPwd.setVisibility(View.GONE);
//                    mEtPhone.setHint(R.string.input_phone_hint);
                }
            }
        });
        mPresenter.checkUpdateVersion(this);
        mEtPhone.setText(SPUtils.getInstance(this).getString(Constants.SPName.USERNAME, ""));

        mAgree.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                 agreeCheckBoxIsTrue = arg1;
            }
        });

    }



    @OnClick({R.id.tv_get_code, R.id.bt_login, R.id.alipayIv, R.id.wechatIv, R.id.tv_service_agreement, R.id.tv_privacy_policy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_get_code:
                String phone = mEtPhone.getText().toString();
                if (TextUtils.isEmpty(phone) || phone.length() != 11) {
                    ToastUtils.showToast("请输入合法的手机号码");
                    return;
                }
                mCodePresenter.onGetCode(this, phone, CodePresenter.MSG_TYPE_LOGIN);
                break;
            case R.id.bt_login:
                TipsDialog();
                break;
            case R.id.alipayIv:
                mType = LoginPresenter.AUTH_TYPE_ALIPAY;
                mPresenter.onGetAlipayAuth(this);
                break;
            case R.id.wechatIv:
                mType = LoginPresenter.AUTH_TYPE_WX;
                if(agreeCheckBoxIsTrue) {
                    onWxAuth(SHARE_MEDIA.WEIXIN);
                }else {
                    ToastUtils.showToast("请阅读并接受用户协议!");
                    return;
                }
                break;
            case R.id.tv_service_agreement:
                CustomServiceActivity.go(this, 0);
                break;
            case R.id.tv_privacy_policy:
                CustomServiceActivity.go(this, 1);
                break;
        }
    }

    private void TipsDialog() {
        final BaseDialog dialog = new BaseDialog(PhoneSmsLoginActivity.this, R.layout.dialog_login_private, Gravity.CENTER, false);
        final TextView tvContent = dialog.getView(R.id.tv_dialog_content);
        setMsgContent(tvContent);
        ((TextView) dialog.getView(R.id.tv_dialog_title)).setText("隐私政策");
        ((TextView) dialog.getView(R.id.btn_cancel)).setText("不同意并退出app");
        ((TextView) dialog.getView(R.id.btn_cancel)).setTextColor(getResources().getColor(R.color.c_333333));
        ((TextView) dialog.getView(R.id.btn_confirm)).setText("同意");
        ((TextView) dialog.getView(R.id.btn_confirm)).setTextColor(getResources().getColor(R.color.white));
        dialog.getView(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.toggleDialog();
                System.exit(0);
            }
        });
        dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SPUtils.getInstance(PhoneSmsLoginActivity.this).putString(Constants.SPName.IS_TIP, "1");
                dialog.toggleDialog();
                tryNext();
            }
        });
        dialog.toggleDialog();
    }

    private void setMsgContent(TextView tvContent) {
        tvContent.setText("欢迎来到欧卓雅，感谢您对欧卓雅的信任和支持！\n" +
                "为了保障客户端的正常运行以及能够向您提供更全面的功能服务，我们将通过《服务协议》和《隐私政策》帮助您了解我们收集、使用、存储和共享个人信息的情况，以及您所享有的相关权利。\n" +
                "具体内容请您详阅" );
        String content = "《用户协议》";
        SpannableString userSpanStr = new SpannableString(content);
        LoginButtonSpan span = new LoginButtonSpan(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomServiceActivity.go(PhoneSmsLoginActivity.this, 0);
            }
        }, R.color.c_047aff);
        userSpanStr.setSpan(span, 0, content.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvContent.append(userSpanStr);
        tvContent.append("和");
        String content2 = "《隐私政策》";
        SpannableString userSpanStr2 = new SpannableString(content2);
        LoginButtonSpan span2 = new LoginButtonSpan(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomServiceActivity.go(PhoneSmsLoginActivity.this, 1);
            }
        }, R.color.c_047aff);
        userSpanStr2.setSpan(span2, 0, content2.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvContent.append(userSpanStr2);
        tvContent.append("全文，我们已采用业内先进的信息保护措施，并会持续优化信息保护技术和安全管理流程，来保护您的个人信息安全。\n");
        tvContent.append("我们将向您申请权限如下和相应说明：\n");
        tvContent.append("1、相机/存储权限：实现头像上传，图片缓存和使用，降低流量消耗。\n");
        tvContent.append("2、位置权限：自动定位配送地址。\n");
        tvContent.append("3、安装应用权限：支持应用内下载和升级。\n");
        tvContent.append("4、获取IMEI和MAC地址：欧卓雅上传到极光推送，而实现定制化推送消息服务。");
        tvContent.setMovementMethod(LinkMovementMethod.getInstance());
    }

    private void tryNext() {
//        Intent intent = new Intent(this, MainActivity.class);
////        intent.putExtra(MainActivity.IS_LOGIN_TYPE, true);
//        startActivity(intent);
        String phone = mEtPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone) || !AppUtils.telPhoneNumber(phone)) {
            ToastUtils.showToast("请输入合法的手机号码!");
            return;
        }
        if (loginMode == LOGIN_MODE_CODE) {
            loginByCode(phone);
        } else {
            loginByPassword(phone);
        }
    }

    private void loginByPassword(String phone) {
        String password = mEtPwd.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            ToastUtils.showToast("密码不能为空!");
            return;
        }
        if(agreeCheckBoxIsTrue) {
            login(phone, password, LoginBean.LOGIN_TYPE_PASS);
        }else {
            ToastUtils.showToast("请阅读并接受用户协议!");
            return;
        }
    }

    private void loginByCode(String phone) {
        String code = mEtCode.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            ToastUtils.showToast("验证码不能为空!");
            return;
        }
        if(agreeCheckBoxIsTrue) {
            login(phone, code, LoginBean.LOGIN_TYPE_CODE);
        }else {
            ToastUtils.showToast("请阅读并接受用户协议!");
            return;
        }
    }


    private void login(String phone, String password, int type) {
        mPresenter.onLogin(this, phone, type, password, null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCodePresenter.detachView();
        mCodePresenter = null;
    }

    @Override
    public void onLoginSuccess(LoginBean loginBean) {
//        判断是否设置密码
        SPUtils.getInstance(this).putInt("paynum", loginBean.getPaynum());
        SPUtils.getInstance(this).putString(Constants.SPName.IS_LOGIN, "1");
        if (SPUtils.getInstance(this).getString(Constants.PREE.IS_PAY_PWD, "").equals("1")) {  //是否设置密码
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            Intent intent = new Intent(this, SetPasswordActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onGetAlipayAuthSuccess(String sdkUrl) {
        onAliPayAuth(sdkUrl);
    }

    @Override
    public void onNeedBindPhone(int type, AlipayAuthBean bean) {
//        if (type == LoginPresenter.AUTH_TYPE_WX) {
//            BindPhoneActivity.go(PhoneSmsLoginActivity.this, type, unionId, wx_useravatar, wx_nickname, wx_sex);
//        } else if (type == LoginPresenter.AUTH_TYPE_ALIPAY) {
//            BindPhoneActivity.go(PhoneSmsLoginActivity.this, type, bean.getUserId(), bean.getAvatar(), bean.getNick_name(), bean.getGender());
//        }
    }

    public void onNeedBindPhone() {
        if (mType == LoginPresenter.AUTH_TYPE_WX) {
            BindPhoneActivity.go(PhoneSmsLoginActivity.this, mType, unionid);
        } else if (mType == LoginPresenter.AUTH_TYPE_ALIPAY) {
            BindPhoneActivity.go(PhoneSmsLoginActivity.this, mType, user_id);
        }
    }

    @Override
    public void checkUpdateVersionSuccess(CheckBean json) {
        if (json != null) {
            int vnumber = json.getVersionMapaz().getVnumber();

            if (vnumber > Utils.getVersionCode(this)) {
                new CheckDialog(PhoneSmsLoginActivity.this, json).show();

            }

        }
    }

    @Override
    public void onGetCodeSuccess(JSONObject jsonObject) {
        ToastUtils.showToast(getString(R.string.have_send_verify_code));
        codeHelper.start();  //开启倒计时
    }

    @Override
    public void onGetCodeFail() {
        codeHelper.reset();  //可以点击
    }

    @Override
    public void handleFailResponse(NetBean netBean) {
        super.handleFailResponse(netBean);
        if (Constants.TransCode.TransCode10001.equals(netBean.getTransCode())) {
            onGetCodeFail();
        }
        if (Constants.TransCode.TransCode10063.equals(netBean.getTransCode())) {
            onNeedBindPhone();
        }
    }

    /**************************************  微信授权  *****************************************/
    /**
     * 微信授权
     *
     * @param
     */
    private void onWxAuth(SHARE_MEDIA share_media) {
        //最新版本微信客户端调用接口后也不再出现授权确认页面，确认在微信客户端切换账号后，
        //再次调用登录接口获取的用户资料变化即可
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(this).setShareConfig(config);

        UMShareAPI.get(this).getPlatformInfo(this, share_media, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                KLog.e("onStart()  微信授权开始");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                KLog.e("onComplete() 成功");
                //微信返回的openID和unionID都可以实现用户标识的需求，二者的区别在于，unionID可以实现同一个开发者账号下的应用之间账号打通的需求

                uid = map.get("uid");     //就是unionid，友盟封装了
                unionid = map.get("unionid");     //就是unionid，友盟封装了
                wx_nickname = map.get("name");        //名字
                String gender = map.get("gender");    //性别
                wx_useravatar = map.get("iconurl");  //头像
                if ("男".equals(gender)) {
                    wx_sex = "1";
                } else {
                    wx_sex = "0";
                }
                mPresenter.onAuthLogin(PhoneSmsLoginActivity.this, LoginPresenter.AUTH_TYPE_WX, "", unionid);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                ToastUtils.showToast("授权失败");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                ToastUtils.showToast("授权取消");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
    /**************************************  微信授权  *****************************************/

    /************************************* 支付宝授权 *****************************************/
    public void onAliPayAuth(final String authInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(PhoneSmsLoginActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(authInfo, true);


                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static final int SDK_AUTH_FLAG = 2;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    HashMap<String, String> authResult = (HashMap<String, String>) msg.obj;

                    String resultStatus = authResult.get("resultStatus");
                    KLog.e("authResult", authResult.toString());
                    if (TextUtils.equals(resultStatus, "9000")) { //授权成功
                        String result = authResult.get("result");
                        //截取auth_code=之后的字符串
                        String str = result.substring(result.indexOf("auth_code="));
                        //截取&之前的字符串
                        String str2 = str.substring(0, str.indexOf("&"));
                        auth_code = str2.replace("auth_code=", "");

                        String str3 = result.substring(result.indexOf("user_id="));
                        //截取&之前的字符串
                        String str4 = str3.substring(0, str3.indexOf("&"));
                        user_id = str4.replace("user_id=", "");
                        mPresenter.onAuthLogin(PhoneSmsLoginActivity.this, LoginPresenter.AUTH_TYPE_ALIPAY, auth_code, "");
                    } else {
                        ToastUtils.showToast("授权失败");
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };
    /************************************* 支付宝授权 *****************************************/
}
